﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using Common;
using DevExpress.XtraEditors;

namespace TaxiDispatchClient
{
    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {
        public LoginForm()
        {
            InitializeComponent();          
        }

        public LoginForm(BackgroundWorker worker)
        {
            InitializeComponent();
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Close();
        }

        private void Login()
        {
            try
            {
               
                Console.WriteLine(DateTime.Now.ToString() + "--CheckUser");

                Model.UserInfo model = MainForm.PositionService.CheckUserWithReturn(
                  txtEdt_UserName.Text, txtEdt_Password.Text);
                if (model != null)
                //if (MainForm.PositionService.CheckUser(txtEdt_UserName.Text, txtEdt_Password.Text))
                {
                    //MainForm.UserName = txtEdt_UserName.Text;                 

                    MainForm.MyUserInfo = model;


                    string posIp = comboBoxEdit_PosIP.Text.Replace(" ","");
                    if (posIp.Contains("(")) posIp = posIp.Remove(posIp.IndexOf('('));
                    Properties.Settings.Default.PositionServerIp = posIp;                        
                    Properties.Settings.Default.Save();

                  
                    double newVersion = 0;
                    double.TryParse(MainForm.PositionService.GetClientVersion(), out newVersion);
                    if (newVersion > MainForm.ClientVersion)
                    {
                        if (MessageBox.Show("最新版本号为V" + newVersion + ",软件需要更新，确定更新吗？",
                            "更新提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            System.Diagnostics.Process.Start(Application.StartupPath + @"\AutoUpdate.exe");
                            Environment.Exit(0);
                        }
                    }

                    this.BeginInvoke(new MethodInvoker(delegate()
                    {

                        IPAddress[] ips = Dns.GetHostAddresses(posIp);
                        if (ips.Length > 0)
                        {
                            // OperateConfig.SaveClientTransferServerIp(ips[0].ToString());
                               
                        }                            
                        MainForm.IsLoginOk = true;
                        // MainForm.UserName = txtEdt_UserName.Text;
                        marqueeProgressBarControl1.Text = "登录成功，正在初始化地图数据。";                      
                        Properties.Settings.Default.PositionServerIp = comboBoxEdit_PosIP.Text;
                        Properties.Settings.Default.Save();
                        
                    }));
                    
                }
                else
                {
                    InitContrlLonginFail("帐号和密码验证失败！");
                }
            }
            catch (Exception ex)
            {
                InitContrlLonginFail("无法连接服务器！");
                Common.CommonRoutine.HandlingExceptions(ex);
            }

        }

        private void InitContrlLonginIng()
        {

            this.BeginInvoke(new MethodInvoker(delegate() { comboBoxEdit_PosIP.Enabled = false; }));
            this.BeginInvoke(new MethodInvoker(delegate() { txtEdt_Password.Enabled = false; }));

            this.BeginInvoke(new MethodInvoker(delegate() { txtEdt_UserName.Enabled = false; }));

            this.BeginInvoke(new MethodInvoker(delegate() { pictureEdit_Login.Enabled = false; }));

            this.BeginInvoke(new MethodInvoker(delegate() { this.marqueeProgressBarControl1.Visible = true; }));

            this.BeginInvoke(new MethodInvoker(delegate() { this.marqueeProgressBarControl1.Text = "正在登录......"; }));

            this.BeginInvoke(new MethodInvoker(delegate()
            {
                this.marqueeProgressBarControl1.Properties.Stopped = false;
            }));



        }

        private void InitContrlLonginFail(string errorstr)
        {

            this.BeginInvoke(new MethodInvoker(delegate()
                                                   {
                                                       comboBoxEdit_PosIP.Enabled = true;
                                                       txtEdt_Password.Enabled = true;
                                                       txtEdt_UserName.Enabled = true;
                                                       pictureEdit_Login.Enabled = true;
                                                       marqueeProgressBarControl1.Properties.Stopped = true;
                                                       marqueeProgressBarControl1.Text = errorstr;
                                                   }));
            this.BeginInvoke(new MethodInvoker(delegate() { }));
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            comboBoxEdit_PosIP.Text = Properties.Settings.Default.PositionServerIp;
        }



        private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Environment.Exit(0);
        }



        Point _mouseOff;
        bool _leftFlag;
        private void LoginForm_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y); 
                _leftFlag = true;                  
            }
        }

        private void LoginForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);  
                Location = mouseSet;
            }
        }

        private void LoginForm_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }



        private void pictureEdit_Login_MouseEnter(object sender, EventArgs e)
        {
            pictureEdit_Login.Image = Properties.Resources.loginButton;
        }

        private void pictureEdit_Login_MouseLeave(object sender, EventArgs e)
        {
            pictureEdit_Login.Image = Properties.Resources.loginButton2;
        }

        private void pictureEdit_Exit_MouseEnter(object sender, EventArgs e)
        {
            pictureEdit_Exit.Image = Properties.Resources.exit2;
        }

        private void pictureEdit_Exit_MouseLeave(object sender, EventArgs e)
        {
            pictureEdit_Exit.Image = Properties.Resources.exit;
        }

        private void pictureEdit_Login_Click(object sender, EventArgs e)
        {
            InitContrlLonginIng();
            if (!Common.CommonRoutine.IsValidIp(comboBoxEdit_PosIP.Text.Trim()))
            {
                InitContrlLonginFail("位置服务器IP输入不正常。");
                comboBoxEdit_PosIP.Focus();
                return;
            }
            try
            {
                string posIp = comboBoxEdit_PosIP.Text.Replace(" ", "");
                if (posIp.Contains("(")) posIp = posIp.Remove(posIp.IndexOf('('));
                if (MainForm.InitWcfService(posIp))
                {
                    Thread t = new Thread(Login);
                    t.Start();
                }
                else
                {
                    InitContrlLonginFail("Wcf服务初始化失败！");
                }
            }
            catch (Exception ex)
            {
                InitContrlLonginFail("无法连接服务器!");
                Common.CommonRoutine.HandlingExceptions(ex, true);
            }
        }

        private void pictureEdit_Exit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void LoginForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;   //将Handled设置为true，指示已经处理过KeyPress事件
                pictureEdit_Login_Click(sender, e);
            }

        }




    }
}